package com.gitee.srurl.system.controller.open;

import com.gitee.srurl.core.annotation.Login;
import com.gitee.srurl.core.dto.result.ShortUrlResultDTO;
import com.gitee.srurl.core.util.login.LoginHelper;
import com.gitee.srurl.core.util.login.OperationUser;
import com.gitee.srurl.system.biz.OpenApiBiz;
import com.gitee.srurl.system.params.GenerateShortUrlParams;
import com.gitee.srurl.system.util.response.R;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zxw
 * @date 2023/4/28 20:29
 */
@RestController
@RequestMapping("open/api")
@RequiredArgsConstructor
public class ShortUrlOpenApiController {

    private final OpenApiBiz openApiBiz;

    @Login(apiAccess = Login.ApiAccess.API)
    @PostMapping("getShortUrl")
    public R<ShortUrlResultDTO> getShortUrl(@RequestBody @Valid GenerateShortUrlParams generateShortUrlParams) {

        ShortUrlResultDTO resultDTO = openApiBiz.getShortUrl(generateShortUrlParams);
        return R.ok(resultDTO);
    }

    /**
     * 短链剩余数据
     *
     * @param shortUrl 短链URL
     * @return
     */
    @Login(apiAccess = Login.ApiAccess.API)
    @GetMapping("shortUrlRemaining")
    public R<ShortUrlResultDTO> shortUrlRemaining(@RequestParam String shortUrl) {

        OperationUser loginUser = LoginHelper.getLoginUser();
        ShortUrlResultDTO resultDTO = openApiBiz.peggingOriginUrl(shortUrl, loginUser);
        if (resultDTO == null) {
            return R.error("该账号下短链不存在或已禁用");
        }
        return R.ok(resultDTO);
    }

    /**
     * 反查原始url
     *
     * @param shortUrl 短链url
     * @return 原始url
     */
    @Login(apiAccess = Login.ApiAccess.API)
    @GetMapping("peggingOriginUrl")
    public R<Map<String, String>> peggingOriginUrl(@RequestParam String shortUrl) {

        OperationUser loginUser = LoginHelper.getLoginUser();
        ShortUrlResultDTO shortUrlResultDTO = openApiBiz.peggingOriginUrl(shortUrl, loginUser);
        if (shortUrlResultDTO == null) {
            return R.error("该账号下短链不存在或已禁用");
        }
        // 避免以后需要添加参数 不直接作为data返回一个url 先暂时转为map返回
        Map<String, String> data = new HashMap<>();
        data.put("originUrl", shortUrlResultDTO.getOriginUrl());
        return R.ok(data);
    }
}
